package points_logic

import (
	"errors"
	"fmt"
	"wx-uniapp-go/internal/repository/dto"
	"wx-uniapp-go/internal/repository/models"
)

// CreatePointsRule 创建积分规则
func (l *PointsLogic) CreatePointsRule(req *dto.CreatePointsRuleReq) error {
	// 检查类型是否已存在
	exists, err := models.Exists(l.Ctx, &models.PointsRule{}, "type = ?", req.Type)
	if err != nil {
		return err
	}
	if exists {
		return errors.New("积分类型已存在")
	}

	rule := &models.PointsRule{
		Type:        req.Type,
		Name:        req.Name,
		Points:      req.Points,
		DayLimit:    req.DayLimit,
		Status:      1, // 默认启用
		Description: req.Description,
	}

	_, err = models.Insert(l.Ctx, rule)
	return err
}

// UpdatePointsRule 更新积分规则
func (l *PointsLogic) UpdatePointsRule(req *dto.UpdatePointsRuleReq) error {
	rule := new(models.PointsRule)
	exists, err := models.Get(l.Ctx, rule, "id = ?", req.Id)
	if err != nil {
		return err
	}
	if !exists {
		return errors.New("规则不存在")
	}

	if req.Name != "" {
		rule.Name = req.Name
	}
	if req.Points != 0 {
		rule.Points = req.Points
	}
	if req.DayLimit >= 0 {
		rule.DayLimit = req.DayLimit
	}
	if req.Status != 0 {
		rule.Status = req.Status
	}
	if req.Description != "" {
		rule.Description = req.Description
	}

	return models.Update(l.Ctx, fmt.Sprintf("id = %d", req.Id), rule)
}

// DeletePointsRule 删除积分规则
func (l *PointsLogic) DeletePointsRule(id int64) error {
	// 检查是否存在
	exists, err := models.Exists(l.Ctx, &models.PointsRule{}, "id = ?", id)
	if err != nil {
		return err
	}
	if !exists {
		return errors.New("规则不存在")
	}

	// 检查是否有关联的积分记录
	exists, err = models.Exists(l.Ctx, &models.UserPointsLog{}, "type = (SELECT type FROM points_rule WHERE id = ?)", id)
	if err != nil {
		return err
	}
	if exists {
		return errors.New("规则已被使用，不能删除")
	}

	return models.Delete(l.Ctx, &models.PointsRule{Id: id}, "")
}

// ListPointsRules 查询积分规则列表
func (l *PointsLogic) ListPointsRules(req *dto.ListPointsRuleReq) (*dto.ListPointsRuleResp, error) {
	rule := &models.PointsRule{}
	where := "1=1"
	var params []interface{}

	if req.Type != "" {
		where += " AND type = ?"
		params = append(params, req.Type)
	}
	if req.Status != 0 {
		where += " AND status = ?"
		params = append(params, req.Status)
	}

	// 获取总数
	total, err := models.Count(l.Ctx, rule, where, params...)
	if err != nil {
		return nil, err
	}

	// 获取列表
	var rules []*models.PointsRule
	_, err = models.FindByPage(l.Ctx, &rules, req.Page, req.Size, where, params...)
	if err != nil {
		return nil, err
	}

	// 转换响应
	list := make([]*dto.PointsRuleResp, len(rules))
	for i, rule := range rules {
		list[i] = &dto.PointsRuleResp{
			Type:        rule.Type,
			Name:        rule.Name,
			Points:      rule.Points,
			DayLimit:    rule.DayLimit,
			Description: rule.Description,
		}
	}

	return &dto.ListPointsRuleResp{
		Total: total,
		List:  list,
	}, nil
}
